package org.maven.dependencybrowser.model;
/**********************************************************************
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Contributors:

**********************************************************************/
import org.apache.maven.project.interpolation.ModelInterpolationException;
import org.maven.dependencybrowser.controller.ArtifactResolver;
import org.maven.dependencybrowser.controller.DependencyResolutionException;
import org.maven.dependencybrowser.implementations.IProgressMeter;
import org.maven.dependencybrowser.implementations.Workspace;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Stack;

public class RootPom extends PomFile
{
    private final Workspace workspace;

    public RootPom(PomFile rootPom, Workspace workspace) throws ArtifactInitialisationException, ModelInterpolationException
    {
        super(rootPom.getModel(), rootPom.getParent(), rootPom.getScope());
        this.workspace = workspace;
    }

    public void resolveDependencies(ArtifactResolver resolver, IProgressMeter progress)
    {
        if (isModulePom())
        {
            progress.resolving(this);
            dependencies = new ArrayList<Artifact>();
            for (Object o : getModel().getAssembledModel().getModules())
            {
                String moduleName = (String) o;
                PomFile module = workspace.loadModulePom(moduleName);
                if (module != null)
                {
                    dependencies.add(module);
                    resolver.addPomToDuplicatesList(module);
                    module.resolveDependencies(resolver, progress, new Stack<LeafDependency>());
                }
                else
                {
                    throw new DependencyResolutionException("Could not find module pom file: " + workspace.getPath(moduleName));
                }
            }
        }
        else
        {
            // resolve as a regular dependency pom
            super.resolveDependencies(resolver, progress, new Stack<LeafDependency>());
        }
    }

    private boolean isModulePom()
    {
        List modules = getModel().getAssembledModel().getModules();
        return modules != null && modules.size() != 0;
    }

}
